package com.web.exiaodao.remote.controller;

import java.util.Map;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.web.exiaodao.business.constant.JConstant;
import com.web.exiaodao.remote.service.ApiUserService;
import com.web.webstart.base.util.XaUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wordnik.swagger.annotations.Api;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiParam;

import com.web.webstart.base.constant.XaConstant;
import com.web.webstart.base.controller.BaseController;
import com.web.webstart.base.exception.BusinessException;
import com.web.webstart.base.util.result.XaResult;
import com.web.webstart.base.util.jpa.WebUitl;
import com.web.exiaodao.remote.service.ApiFavoriteTableService;
import com.web.exiaodao.remote.vo.FavoriteTableVo;
import com.web.exiaodao.business.entity.FavoriteTable;

/**
 * @author zhanglin
 * @version V1.0
 * @Title: ApiFavoriteTableController.java
 * @Package com.web.exiaodao.remote.controller
 * @Description: 收藏表信息接口
 * @date 2015年3月23日 下午1:00:00
 */
@Api(value = "Favorite", description = "收藏接口", position = 10)
@Controller
@RequestMapping("/api/favorite")
public class ApiFavoriteTableController extends BaseController {

    private static final Logger LOGGER = Logger.getLogger(ApiFavoriteTableController.class);

    @Autowired
    private ApiFavoriteTableService favoriteTableService;

    @Autowired
    private ApiUserService userService;

    /**
     * @return
     * @Title: findFavoriteTableList
     * @Description: 查询所有收藏表信息
     */
    @ApiOperation(value = "查询所有收藏列表", notes = "查询所有收藏表信息,当返回的code=1时，取出object进行显示,存放为数组对象")
    @ResponseBody
    @RequestMapping(value = "findFavoriteList", method = RequestMethod.POST)
    public XaResult<List<FavoriteTableVo>> findFavoriteList(
            @ApiParam("申请人ID,字段名:userId") @RequestParam(value = "userId") Long userId,
            @ApiParam("页号,字段名:nextPage,默认0,从第0页开始") @RequestParam(defaultValue = "0") Integer nextPage,
            @ApiParam("页长,字段名:pageSize,默认10") @RequestParam(defaultValue = "10") Integer pageSize
    ) throws BusinessException {
        XaResult<List<FavoriteTableVo>> xr = new XaResult<>();
        if (XaUtil.isEmpty(userId)) {
            xr.error("用户id不能为空");
            return xr;
        }
        Pageable pageable = WebUitl.buildPageRequest(nextPage, pageSize, "[{property:'createTime',direction:'DESC'}]");
        Map<String, Object> filterParams = WebUitl.getParametersStartingWith(
                "{'search_EQ_favoriteState':'"+ JConstant.BooleanStatus.TRUE +"'" +
                        ",'search_EQ_userId':'"+userId+"'}", "search_");
        return favoriteTableService.findListEQStatusByFilter(XaConstant.Status.valid, filterParams, pageable);
    }

    /**
     * @return
     * @Title: save
     * @Description: 新增一条实体
     */
    @ApiOperation(value = "新增收藏", notes = "新增收藏表,当返回的code=1时，保存成功后object返回对象")
    @ResponseBody
    @RequestMapping(value = "addFavorite", method = RequestMethod.POST)
    public XaResult<FavoriteTableVo> addFavorite(
            @ApiParam("2机构;22住;3商城;4玩;42:作者;游学5;服务公共1;12:家政护理; 13:医疗服务|医疗康复; 14:护理培训|培训义工 15:义工中心 ,字段名:type") @RequestParam(value = "type") long type,
            @ApiParam("收藏对象ID,字段名:favorite_ObjectID") @RequestParam(value = "favorite_ObjectID") Long favorite_ObjectID,
            @ApiParam("收藏人员ID,字段名:userId") @RequestParam(value = "userId") Long userId,
            HttpServletRequest request
    ) throws BusinessException {
        XaResult<FavoriteTableVo> xr = new XaResult<FavoriteTableVo>();
        if (XaUtil.isEmpty(userId)) {
            xr.error("用户id不能为空");
            return xr;
        }
        try {
            //用户要存在
            userService.findOne(userId);

            if (XaUtil.isEmpty(type)) {
                xr.error("type不能为空");
                return xr;
            }
            if (XaUtil.isNotEmpty(type) && !JConstant.Search_Share_FavType.isConstantVal(type)) {
                xr.error("type错误");
                return xr;
            }
            FavoriteTable model = new FavoriteTable();
            model.setFavoriteObjectId(favorite_ObjectID + "");
            model.setUserId(userId);
            model.setType(type+"");
            return favoriteTableService.createModel(model);
        } catch (Exception e) {
            xr.error(XaConstant.Message.error);
            LOGGER.error(XaConstant.Message.error, new Throwable(e));
        }
        return xr;
    }

    /**
     * @return
     * @Title:
     * @Description: 修改一条实体
     */
    @ApiOperation(value = "取消收藏", notes = "取消收藏,当返回的code=1时，保存成功后object返回对象")
    @ResponseBody
    @RequestMapping(value = "cancelFavorite", method = RequestMethod.POST)
    public XaResult<FavoriteTableVo> cancelFavorite(
            @ApiParam("收藏人员ID,字段名:userId") @RequestParam(value = "userId") Long userId,
            @ApiParam("收藏实体id,字段名:tId") @RequestParam(value = "tId") Long tId,
            HttpServletRequest request
    ) throws BusinessException {
        XaResult<FavoriteTableVo> xr = new XaResult<FavoriteTableVo>();
        if (XaUtil.isEmpty(userId)) {
            xr.error("用户id不能为空");
            return xr;
        }
        try {
            //用户要存在
            userService.findOne(userId);

            Boolean isFav = favoriteTableService.findOne(tId).getObject().getFavoriteState();
            if (!isFav) {
                xr.error("取消收藏失败:你还没有收藏!");
                return xr;
            }

            FavoriteTable model = new FavoriteTable();
            model.setFavoriteState(false);
            model.setId(tId);
            return favoriteTableService.updateModel(model);
        } catch (Exception e) {
            xr.error(XaConstant.Message.error);
            LOGGER.error(XaConstant.Message.error, new Throwable(e));
        }
        return xr;
    }
}

